<?php
class ListNode {
    public $val = 0;
    public $next = null;
    function __construct($val)
    {
        $this->val = $val;
    }
}

class Solution
{
    /**
     * @param ListNode $head
     * @param Integer $n
     * @return ListNode
     */
    function removeNthFromEnd($head, $n)
    {
        $_p = new ListNode(-1);
        $_p->next = $head;
        $p1 = $p2 = $_p;

        while ($n>=0) {
            $p2 = $p2->next;
            $n--;
        }

        while ($p2 != null) {
            $p1 = $p1->next;
            $p2 = $p2->next;
        }

        $p1->next = $p1->next->next;

        return $_p->next;
    }
}